package com.rags.chess.move;

import com.rags.chess.base.Coordinate;
import com.rags.chess.base.Piece;
import com.rags.chess.base.PieceType;
import com.rags.chess.game.Game;
import com.rags.chess.pieces.Bishop;
import com.rags.chess.pieces.Knight;
import com.rags.chess.pieces.Pawn;
import com.rags.chess.pieces.Queen;
import com.rags.chess.pieces.Rook;

public class PawnPromotionMove extends Move {
	private Piece promotionPiece;
	
	public PawnPromotionMove(Game game, Coordinate start, Coordinate anEnd, PawnPromotionMoveListener aPawnPromotionMoveListener) {
		super(game, start, anEnd, aPawnPromotionMoveListener);
	}

	@Override
	protected String deriveNotation(Game game, Coordinate start, Coordinate end) {
		Piece startPiece = game.getPiece(start);
		if (!(startPiece instanceof Pawn))
			throw new IllegalArgumentException(String.format("Only a pawn can promote: %s", startPiece.getClass().getSimpleName()));
		if (end.getNotation().charAt(1) != '1' && end.getNotation().charAt(1) != '8')
			throw new IllegalArgumentException(String.format("Pawn Promotion can only happen on the 1st or 8th ranks: %s", end));
		if (!startPiece.isValidMove(game, end))
			throw new IllegalArgumentException(String.format("Illegal Pawn Promotion Move attempted: %s%s to %s", startPiece.getNotation(), start, end));
			
		if (game.getPiece(end) == null)
			return String.format("%s%s=%s", startPiece.getNotation(), end, getNewPiece(startPiece, end));
		return String.format("%sx%s=%s", start.getNotation().charAt(0), end, getNewPiece(startPiece, end));
	}

	@Override
	public void makeMove(Game game, Coordinate start, Coordinate end) {
		Piece p = game.getPiece(start);
		Piece toBeCaptured = game.getPiece(end); 
		if (toBeCaptured != null)
			game.removePiece(toBeCaptured);
		
		p.setPosition(end);
		game.getSquare(start).setPiece(null);
		game.getSquare(end).setPiece(promotionPiece);
		game.removePiece(p);
		game.addPiece(promotionPiece);
	}
	
	private String getNewPiece(Piece startPiece, Coordinate end) {
		PieceType pieceType = ((PawnPromotionMoveListener)getMoveCallbackListener()).returnPawnPromotionPiece();
		if (PieceType.Queen.equals(pieceType)) promotionPiece = new Queen(startPiece.getColor(), end);
		else if (PieceType.Rook.equals(pieceType)) promotionPiece = new Rook(startPiece.getColor(), end);
		else if (PieceType.Knight.equals(pieceType)) promotionPiece = new Knight(startPiece.getColor(), end);
		else if (PieceType.Bishop.equals(pieceType)) promotionPiece = new Bishop(startPiece.getColor(), end);
		else throw new IllegalArgumentException(String.format("Invalid pawn promotion piece: %s", pieceType));
		
		return promotionPiece.getNotation();
	}
}
